package it.low.game.client.gui.graphics;

import it.low.game.client.util.ClientLogManager;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;

import javax.swing.ImageIcon;

public class MapBackground extends Rectangle {

	private MapBackgroundTile[][] mapBackgroundTiles = null;
	
	public MapBackground(int nTilesX, int nTilesY){
		this.setLocation(0,0);
		this.setSize(0,0);
		this.mapBackgroundTiles = new MapBackgroundTile[nTilesX][nTilesY];				
	}
	
	public MapBackground(Point offset, int nTilesX, int nTilesY){
		this.setLocation(offset);
		this.setSize(0,0);
		this.mapBackgroundTiles = new MapBackgroundTile[nTilesX][nTilesY];				
	}
	
	private int getNumberMapBackgroundTileX(){
		return this.mapBackgroundTiles.length;
	}
	
	private int getNumberMapBackgroundTileY(){
		return this.mapBackgroundTiles[0].length;
	}
	
	private MapBackgroundTile getMapBackgroundTile(int tileX, int tileY) {
		if (tileX < 0 || tileX >= getNumberMapBackgroundTileX() || tileY < 0 || tileY >= getNumberMapBackgroundTileY())
		{
			return null;
		}
		else {
			return this.mapBackgroundTiles[tileX][tileY];
		}
	}
	
	private Point getTileAbsolutePoint(int tileX, int tileY){
		double absPointX = 0, absPointY = 0;
		for(int ix=0 ; ix<tileX ; ix++){
			absPointX += this.getMapBackgroundTile(ix,tileY).getWidth();
		}
		for(int iy=0 ; iy<tileY ; iy++){
			absPointY += this.getMapBackgroundTile(tileX,iy).getHeight();
		}			
		return new Point((int)absPointX,(int)absPointY);
	}
	
	private Point getTileRelativeLocation(int tileX, int tileY){
		Point absLocation = getTileAbsolutePoint(tileX,tileY);
		return new Point(absLocation.x+this.x,absLocation.y+this.y);
	}
	
	public void setBGMapTile(int tilesX, int tilesY, ImageIcon imageIcon) {
		Point relativeLocation = this.getTileRelativeLocation(tilesX, tilesY); 
		ClientLogManager.logMsg("call setBGMapTile() relatLoc = "+relativeLocation);
		MapBackgroundTile mapBackgroundTile = new MapBackgroundTile(relativeLocation,imageIcon);
		this.mapBackgroundTiles[tilesX][tilesY] = mapBackgroundTile;
		int width = relativeLocation.x + (int)mapBackgroundTile.getWidth() - this.x;
		int height = relativeLocation.y + (int)mapBackgroundTile.getHeight() - this.y;
		this.width = (this.width>=width)?this.width:width;
		this.height = (this.height>=height)?this.height:height;
	}
	
	public void draw(Graphics g){
		// DRAW THE MAP BACKGROUND TILES		
		for(int ix=0 ; ix<this.getNumberMapBackgroundTileX() ; ix++){
			for(int iy=0 ; iy<this.getNumberMapBackgroundTileY() ; iy++){
				this.getMapBackgroundTile(ix, iy).draw(g);
			}
		}		
	}
	
}
